package com.xyy.saas.payment.callback.core.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.adpater.pingxx.domain.PayDO;
import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.dao.model.PrePayOrder;
import com.xyy.saas.payment.payment.core.service.PrePayOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: wuqiongda
 * @Date: 2020/3/2 19:40
 */
@Component
@Deprecated
public class AliPaySuccessHandler implements BaseHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliPaySuccessHandler.class);

    @Autowired
    private CallbackRunner callbackRunner;
    @Autowired
    private PrePayOrderService prePayOrderService;

    @Override
    public String getMethod() {
        return Constants.METHOD_ALIPAY_SUCCESS_NAME;
    }

    @Override
    public boolean callBackHandler(Object domain) {
        PayDO payDO = (PayDO)domain;
        LOGGER.info("AliPaySuccessHandler callBackHandler alipay callback {}", JSONObject.toJSONString(payDO));

        if (domain==null){
            LOGGER.error("AliPaySuccessHandler callBackHandler alipay callback fail domain is null");
            return false;
        }
        //校验是否成功
        //退款也会回调这个接扣，这里就不是trade success了
        if (!"TRADE_SUCCESS".equals(payDO.getResultCode())) {
            LOGGER.info("AliPaySuccessHandler callBackHandler ResultCode is not success payDO:{}", JSON.toJSON(payDO));
            return true;
        }
        PrePayOrder prePayOrder = prePayOrderService.getPrePayOrderByPayNo(payDO.getOrderNo());
        if (prePayOrder==null||!prePayOrder.getAmount().equals(payDO.getAmount())){
            LOGGER.error("AliPaySuccessHandler callBackHandler prePayOrder is null or amount atypism prePayOrder:{}, payDO:{}", JSON.toJSON(prePayOrder), JSON.toJSON(payDO));
            return false;
        }
        //校验订单金额是否一致
        if (!payDO.getAmount().equals(prePayOrder.getAmount())){
            LOGGER.error("AliPaySuccessHandler callBackHandler error amount not Agreement payNO:{}, wxAmount:{}, prepayAmount:{}", payDO.getOrderNo(), payDO.getAmount(), prePayOrder.getAmount());
            return true;
        }
        payDO.setCount(0);
        payDO.setBusinessType(prePayOrder.getBusinessType());
        payDO.setBusinessOrderType(prePayOrder.getBusinessOrderType());
        payDO.setReceiverId(prePayOrder.getReceiverId());
        payDO.setCallbackAddress(prePayOrder.getCallbackAddress());
        payDO.setBusinessOrderNo(prePayOrder.getBusinessOrderNo());
        callbackRunner.aliPaySuccessCallback(payDO);
        return true;
    }
}
